package com.ly.hotel.spainterface.jg.view;

import android.app.Dialog;
import android.app.DialogFragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.spainterface.jg.bean.MassageItem;
import com.ly.hotel.spainterface.jg.bean.MassageItemCarBean;
import com.ly.hotel.spainterface.jg.bean.OnOrderGoodsSuccess;
import com.ly.hotel.spainterface.jg.bean.OnSwipeCardListener;
import com.ly.hotel.spainterface.jg.bean.gson.consume.ConsumeListPara;
import com.ly.hotel.spainterface.jg.bean.gson.consume.ConsumePara;
import com.ly.hotel.spainterface.jg.bean.gson.consume.consumeback.ConsumeParas;
import com.ly.hotel.spainterface.jg.bean.gson.consume.consumeback.ConsumeParasResult;
import com.ly.hotel.spainterface.jg.bean.gson.handcard.HandCard;
import com.ly.hotel.spainterface.jg.bean.gson.handcard.HandCardResult;
import com.ly.hotel.spainterface.jg.bean.gson.postJson.TableChipPara;
import com.ly.hotel.spainterface.jg.utils.DecToHexUtils;
import com.ly.hotel.spainterface.jg.utils.GsonUtils;
import com.ly.hotel.spainterface.jg.utils.OkHttpUtils;
import com.ly.hotel.spainterface.jg.utils.SwipeCardUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ThinkPad on 2018/3/12.
 */

public class CustomOrderFromCarDialog extends DialogFragment implements OnSwipeCardListener{

    private String cardIdHex;
    private String cashierIP;
    private String cashierPORT;
    private int[] judgeNum = {0,1,2};
    private CustomLoadingDialog loadingDialog;
    private List<MassageItem> massageItems;
    private String categoryName;
    private OnOrderGoodsSuccess onOrderGoodsSuccess;
    private SwipeCardUtils swipeCardUtils;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    String resultString = msg.obj.toString();
                    if(msg.arg1 == judgeNum[0]){
                        swipeCardUtils.cancelBandNo(false);
                        Log.d("JgActivity", "手牌号转ID号接口返回：" + resultString);
                        HandCardResult handCardResult = GsonUtils.parseSimpleJson(resultString,HandCardResult.class);
                        if(handCardResult.isSuccess()){
                            HandCard handCard = handCardResult.getResult();
                            String tableChipId = handCard.getTableChipId();// 转成16进制的芯片号
                            String tableCode = handCard.getTableCode();// 返回的手牌号
                            Log.d("getBandNo", tableChipId + "-" + tableCode);
                            if(tableChipId != null && tableCode != null){
                                consumeInput(tableCode);
                            }else{
                                loadingDialog.close();
                                dismiss();// 关闭窗口
                                CustomToast customToast = CustomToast.makeText(MyApplication.getContext(),"手牌有误，请联系服务员！", Toast.LENGTH_SHORT,false);
                                customToast.setGravity(Gravity.CENTER,0,0);
                                //customToast.showMyToast(5000);
                                customToast.show();
                            }
                        }
                    }else if(msg.arg1 == judgeNum[1]){
                        Log.d("JgActivity", "消费录单接口返回：" + resultString);
                        loadingDialog.close();
                        ConsumeParasResult consumeParaResult = GsonUtils.parseSimpleJson(resultString,ConsumeParasResult.class);
                        if(consumeParaResult.isSuccess()){
                            ConsumeParas consumeParas = consumeParaResult.getResult();
                            if(consumeParas.getErrorMsg() != null){
                                CustomToast customToast = CustomToast.makeText(MyApplication.getContext(),"下单成功，请您耐心等待！",Toast.LENGTH_LONG,true);
                                customToast.setGravity(Gravity.CENTER,0,0);
                                customToast.showMyToast(5000);
                                onOrderGoodsSuccess.orderGoodsSuccess(true);
                            }else{
                                CustomToast customToast = CustomToast.makeText(MyApplication.getContext(),"下单失败，请呼叫服务员手动下单！",Toast.LENGTH_LONG,false);
                                customToast.setGravity(Gravity.CENTER,0,0);
                                customToast.showMyToast(5000);
                            }
                        }
                        dismiss();// 关闭窗口
                    }
                    break;
                case 2:
                    loadingDialog.close();
                    CustomToast customToast = CustomToast.makeText(MyApplication.getContext(),"网络异常，请呼叫服务员处理！",Toast.LENGTH_SHORT,false);
                    customToast.setGravity(Gravity.CENTER,0,0);
                    //customToast.showMyToast(5000);
                    customToast.show();
                    break;
                default:
                    break;
            }
        }
    };

    public void setOnOrderGoodsSuccess(OnOrderGoodsSuccess onOrderGoodsSuccess) {
        this.onOrderGoodsSuccess = onOrderGoodsSuccess;
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            dialog.getWindow().setLayout((int) (dm.widthPixels * 0.5), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        Window window = dialog.getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        //layoutParams.windowAnimations = R.style.customDialogAnim;
        window.setAttributes(layoutParams);
    }

    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);

        Bundle bundle = getArguments();
        cashierIP = bundle.getString("cashierIP");
        cashierPORT = bundle.getString("cashierPORT");
        categoryName = bundle.getString("categoryName");
        MassageItemCarBean massageItemCarBean = (MassageItemCarBean) bundle.getSerializable("massageItemCarBean");
        massageItems = massageItemCarBean.getMassageItems();
        Log.d("JgActivity", cashierIP + ":" + cashierPORT);
        Log.d("JgActivity", massageItems.size() + "");

        int num = 0;
        double priceTotal = 0;
        for(int i = 0; i < massageItems.size(); i ++){
            int goodsNum = massageItems.get(i).getNum();
            double goodsPrice = massageItems.get(i).getPrice();
            num += goodsNum;
            priceTotal += goodsNum * goodsPrice;
        }

        View view = inflater.inflate(R.layout.jg_order_from_car_layout,container,false);
        ImageButton orderFromCarClose = view.findViewById(R.id.order_from_car_close);
        TextView goodsNum = view.findViewById(R.id.goods_num);
        TextView priceSubTotal = view.findViewById(R.id.price_sub_total);
        goodsNum.setText(num + "");
        priceSubTotal.setText("￥" + priceTotal + "元");

        swipeCardUtils = new SwipeCardUtils();
        swipeCardUtils.setOnSwipeCardListener(this);
        swipeCardUtils.swipecard();

        orderFromCarClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                swipeCardUtils.cancelBandNo(false);
                dismiss();
            }
        });
        return view;
    }

    @Override
    public void swipeCardListener(String cardId) {
        Log.d("JgActivity","getBandNo---" + cardId);
        cardIdHex = new DecToHexUtils().getDecToHex(cardId);
        Log.d("JgActivity","getBandNo---" + cardIdHex);
        loadingDialog = new CustomLoadingDialog(getActivity(),"手牌验证中...");
        loadingDialog.show();
        cardIdToCardNo();
    }

    // 调用手牌ID转手牌号接口
    public void cardIdToCardNo(){
        TableChipPara tableChipPara = new TableChipPara();
        tableChipPara.setTableChipId(cardIdHex);
        Gson gson = new Gson();
        String jsonString = gson.toJson(tableChipPara);
        String url = "http://" + cashierIP + ":" + cashierPORT + "/TsInterface/Ts_GetTableCodeByChipId";
        OkHttpUtils.getInstance().postJsonResource(jsonString,url,handler,judgeNum[0]);
    }

    // 消费录入
    public void consumeInput(String tableCode){
        if(massageItems != null && massageItems.size() > 0){
            List<ConsumePara> consumeParas = new ArrayList<>();
            for(int i = 0;i < massageItems.size();i ++){
                ConsumePara consumePara = new ConsumePara();
                consumePara.setGoodsId(massageItems.get(i).getId());
                consumePara.setPrice(massageItems.get(i).getPrice());
                consumePara.setGoodsName(massageItems.get(i).getName());
                consumePara.setNumberCount(massageItems.get(i).getNum());
                consumePara.setArea("A101");// 暂时这样这样用着
                consumeParas.add(consumePara);
            }
            ConsumeListPara consumeListPara = new ConsumeListPara();
            consumeListPara.setLstCosnumepara(consumeParas);
            consumeListPara.setTableCode(tableCode);
            consumeListPara.setDepartmentName(categoryName);
            Gson gson = new Gson();
            String jsonString  = gson.toJson(consumeListPara);
            String url = "http://" + cashierIP + ":" + cashierPORT + "/TsInterface/Ts_AddConsumeList";
            OkHttpUtils.getInstance().postJsonResource(jsonString,url,handler,judgeNum[1]);
        }
    }
}
